﻿using Shop.Collect;
using Shop.Model.Goods;
using Shop.Model.GoodsSku;
using Shop.Model.Stock;
using Shop.RemoteModel;
using Shop.RemoteModel.Stock.Model;
using Shop.Service.Interface;
using WeDonekRpc.Client;
using WeDonekRpc.Helper;
using WeDonekRpc.Model;

namespace Shop.Service.Extend
{
    internal class GoodsStockService : IGoodsStockService
    {
        private readonly IGoodsCollect _Goods;
        private readonly IGoodsSkuCollect _Sku;
        private readonly IGoodsStockCollect _Service;

        public GoodsStockService (IGoodsCollect goods, IGoodsSkuCollect sku, IGoodsStockCollect service)
        {
            this._Goods = goods;
            this._Sku = sku;
            this._Service = service;
        }

        public PagingResult<GoodsStockDto> Query (StockQueryParam query, IBasicPage paging)
        {
            GoodsQuery param = query.ConvertMap<StockQueryParam, GoodsQuery>();
            param.Status = new GoodsStatus[]
            {
                GoodsStatus.已发布
            };
            GoodsBase[] list = this._Goods.Query<GoodsBase>(param, paging, out int count);
            if (list.IsNull())
            {
                return new PagingResult<GoodsStockDto>();
            }
            long[] goodsId = list.ConvertAll(c => c.Id);
            GoodsStockDto[] dtos = list.ConvertMap<GoodsBase, GoodsStockDto>();
            StockDto[] stocks = this._Service.GetStocks<StockDto>(goodsId);
            GoodsSkuBase[] skus = this._Sku.GetsByGoodsId<GoodsSkuBase>(goodsId);
            dtos.ForEach(c =>
            {
                c.SkuStock = skus.Convert(a => a.GoodsId == c.Id, a =>
                {
                    StockDto stock = stocks.Find(b => b.SkuId == a.SkuId);
                    return new SkuStock
                    {
                        GoodsSku = a.GoodsSku,
                        SkuId = a.SkuId,
                        SkuName = a.SkuName,
                        SkuImg = a.SkuImg,
                        SpecsShow = a.SpecsShow,
                        CurStock = stock.CurStock,
                        OutStock = stock.OutStock + stock.LockStock,
                        LastOutTime = stock.LastOutTime
                    };
                });
                if (query.Stock.HasValue)
                {
                    c.SkuStock = c.SkuStock.FindAll(a => a.CurStock <= query.Stock.Value);
                }
            });
            return new PagingResult<GoodsStockDto>(dtos, count);
        }
    }
}
